<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="固件名称" prop="firmwareid">
        <el-select v-model="queryParams.firmwareid" placeholder="请选择固件" style="width: 200px" filterable="true" clearable>
          <el-option
            v-for="dict in firmwaresAllLists"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="固件类型" prop="firmware">
        <el-select v-model="queryParams.firmware" placeholder="请选择固件类型" style="width: 200px" clearable>
          <el-option
            v-for="dict in firmware_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
               v-model="dateRange"
               value-format="YYYY-MM-DD"
               type="daterange"
               range-separator="-"
               start-placeholder="开始日期"
               end-placeholder="结束日期"
            ></el-date-picker>
         </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="creatOTA"
          v-hasPermi="['system:post:add']"
          >创建OTA任务</el-button
        >
      </el-col>-->
      <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:post:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:post:remove']"
            >删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Download"
               @click="handleExport"
               v-hasPermi="['system:post:export']"
            >导出</el-button>
         </el-col> -->
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="otaList"
      @selection-change="handleSelectionChange"
      small
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column
        label="序号"
        width="60"
        align="center"
        fixed="left"
        prop="index"
      >
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column> -->
      <el-table-column label="任务编号" prop="id" fixed="left"/>
      <!-- show-overflow-tooltip -->
      <el-table-column label="固件名称 - 版本号 - 是否量产" min-width="340" align="center" prop="firmware">
        <template #default="scope">
<!-- 假设在 setup 里已经定义了 savePath 变量 -->
<!-- 这里仅展示模板部分修改后的代码 -->
          <!-- <el-tooltip :content="savePath + (scope.row.firmware?.path?.split('/').pop() || '')" placement="top">
            <template #content> -->
              <!-- {{ scope.row.firmware?.path?.split('/').pop() || '' }} -->
            <!-- </template>
            <el-link 
              :href="savePath + (scope.row.firmware?.path?.split('/').pop() || '')" 
              target="_blank"
            > -->
              <span>{{scope.row.firmware? `${scope.row.firmware?.name} - ${scope.row.firmware?.version}(BIN) - ${scope.row.firmware?.isprod?'是':'否'}`:''}}</span>
            <!-- </el-link>
          </el-tooltip> -->
          <br v-if="scope.row.firmware&&scope.row.firmware1"/>
          <!-- <el-tooltip :content="savePath + (scope.row.firmware1?.path?.split('/').pop() || '')" placement="top">
            <template #content>
              {{savePath + (scope.row.firmware1?.path?.split('/').pop() || '') }}
            </template>
            <el-link 
              :href="savePath + (scope.row.firmware1?.path?.split('/').pop() || '')" 
              target="_blank"
            > -->
              <span>{{scope.row.firmware1? `${scope.row.firmware1?.name} - ${scope.row.firmware1?.version}(FS)`:''}}</span>
            <!-- </el-link>
          </el-tooltip> -->
        </template>
      </el-table-column>
      <el-table-column label="固件类型" min-width="120" prop="firmwareType">
        <template #default="scope">
          <dict-tag v-if="scope.row.firmware&&scope.row.firmware1" :options="firmware_type" :value="[scope.row.firmware.firmwareType, scope.row.firmware1?.firmwareType]" />
          <dict-tag v-else :options="firmware_type" :value="scope.row[scope.row.firmware?'firmware':'firmware1']['firmwareType']" />
        </template>
      </el-table-column>
      <el-table-column label="网关MAC" show-overflow-tooltip align="center" prop="gw_mac" min-width="140"/>
      <el-table-column label="网关全部" align="center" prop="gw_full">
        <template #default="scope">
          <el-tag v-if="scope.row.gw_full==true" type="primary">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
                  </template>
      </el-table-column>
      <el-table-column label="手环MAC" show-overflow-tooltip align="center" prop="wb_mac" min-width="160"/>
      <el-table-column label="手环全部" align="center" prop="wb_full">
        <template #default="scope">
          <el-tag v-if="scope.row.wb_full==true" type="primary">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="升级模式" align="center" prop="updateMode">
        <template #default="scope">
          <dict-tag v-if="scope.row.updateMode" :options="ota_update_mode" :value="scope.row.updateMode" />
        </template>
      </el-table-column>
      <el-table-column label="升级时限" align="center" prop="duration" />
      <el-table-column 
        label="手环限量" 
        align="center" 
        prop="wb_count" 
      >
        <template #header>
          <el-tooltip :content="'手环升级数量限制'" placement="top">
            <template #content>
              手环升级数量限制
            </template>
            <span>{{ $slots.header?.({ column: { label: '手环限量' } }) || '手环限量' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <!-- <el-table-column label="强制更新" align="center" prop="force">
        <template #default="scope">
          <el-tag v-if="scope.row.force==true" type="primary">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="长期更新" align="center" prop="remain">
        <template #default="scope">
          <el-tag v-if="scope.row.remain==true" type="primary">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="状态" align="center" prop="action">
        <template #default="scope">
          <dict-tag :options="action_ota" :value="scope.row.action" />
        </template>
      </el-table-column> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="time"
        width="180"
      />
      <!-- <el-table-column label="进度" align="center" prop="value"/> -->
      <el-table-column
        label="操作"
        fixed="right"
        width="200"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Tools"
            @click="handleUpgrade(scope.row)">升级</el-button>
          <el-button v-if="scope.row.firmware?.firmwareType === 'wb-app'" link type="primary" icon="Notebook" @click="() => handleRecord(scope.row)">记录</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']">删除</el-button>
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
            >修改</el-button>
           -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="OTARef"
        :model="form"
        :rules="form.radio == 1 ? rules : ''"
        label-width="120px"
        @submit.prevent
      >
      <el-form-item label="任务名称" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入任务名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="固件类型" prop="radio">
        <el-radio-group v-model="form.radio" class="ml-4" @change="resetFirmwareIds">
          <el-radio :label="1" size="middle">手环固件</el-radio>
          <el-radio :label="2" size="middle">网关固件</el-radio>
        </el-radio-group>
      </el-form-item>
        <!-- <el-form-item label="固件类型" prop="firmwareType">
          <el-select
            v-model="form.firmwareType"
            placeholder="请选择固件类型"
            disabled
            style="width: 260px"
          >
            <el-option
              v-for="dict in firmware_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
          &nbsp;&nbsp;&nbsp;<el-checkbox v-if="form.firmwareType == 'gw-bin'" true-value="1" false-value="0" v-model="form.full">完整固件</el-checkbox>
        </el-form-item> -->
        <el-form-item v-if="form.radio == 1" label="手环固件" prop="firmwareid">
          <el-select v-model="form.firmwareid" placeholder="请选择手环固件" @change="(value) => firmwareChange('wb', value)" style="width: 260px">
            <el-option
              v-for="dict in firmwaresLists.wb"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.radio == 2" label="网关固件(BIN)" prop="firmwareid">
          <el-select v-model="form.firmwareid" placeholder="请选择bin格式固件" @change="(value) => firmwareChange('bin', value)" style="width: 260px">
            <el-option
              v-for="dict in firmwaresLists.bin"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.radio == 2" label="固件 FS 格式" prop="firmwareid_1">
          <el-select v-model="form.firmwareid_1" placeholder="请选择fs格式固件" @change="(value) => firmwareChange('fs', value)" style="width: 260px">
            <el-option
              v-for="dict in firmwaresLists.fs"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.radio == 1" label="路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入路径" style="width: 260px"/>
        </el-form-item>
        <!-- <el-form-item v-if="form.firmwareType === 'gw-bin' || form.firmwareType === 'gw-fs'" label="网关" prop="gw_mac"> -->
        <el-form-item v-if="form.radio" label="网关MAC地址" prop="gw_mac">
          <el-select clearable 
            v-model="form.gw_mac"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入网关"
            :multiple-limit="10"
            style="width: 260px"
            :disabled="form.gw_full===1"
            >
            <el-option v-for="item in gatewayList" :key="item.mac" :label="item.mac" :value="item.mac" />
          </el-select>
          <!-- <el-input v-model="form.gw_mac" placeholder="请输入网关" style="width: 260px"/> -->
          &nbsp;&nbsp;&nbsp;
          <el-checkbox :true-value="1" :false-value="0" v-model="form.gw_full" @change="gwFullChange($event)" :disabled="form.isprod=='true'">全部</el-checkbox>
        </el-form-item>
        <el-form-item v-if="form.radio == 1" label="手环MAC地址" prop="wb_mac">
          <el-select
            v-model="form.wb_mac" 
            multiple
            filterable
            allow-create
            placeholder="请选择或输入手环网关"
            clearable
            :multiple-limit="50"
            style="width: 260px"
            :disabled="form.wb_full===1"
            >
            <el-option v-for="item in wristbandList" :key="item.mac" :label="item.mac" :value="item.mac" />
          </el-select>
          &nbsp;&nbsp;&nbsp;
          <el-checkbox :true-value="1" :false-value="0" v-model="form.wb_full" @change="wbMacChange($event)">全部</el-checkbox>
        </el-form-item>
        <!-- "uponly" | "updown" | "force", -->
        <el-form-item label="升级模式" prop="updateMode">
          <el-radio-group v-model="form.updateMode" class="ml-4">
            <el-radio
              v-for="item in ota_update_mode"
              :key="item.value"
              :label="item.value"
              size="middle"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
          <!-- <el-text type="danger" size="small">开启固件可升级非当前版本，反之只可升级大于当前版本。</el-text> -->
        </el-form-item>
        <el-form-item v-if="form.radio == 1" label="升级限制" prop="updateLimit">
          <el-radio-group v-model="form.updateLimit" class="ml-4">
            <el-radio
              v-for="item in ota_update_limit"
              :key="item.value"
              :label="item.value"
              size="middle"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.radio == 1&&form.updateLimit==1" label="升级时限" prop="duration">
          <el-input-number
            v-model="form.duration"
            placeholder="请输入手环升级时长限制"
            class="mx-4"
            :min="0"
            :max="86400"
            :step="1"
            step-strictly
            controls-position="right"
            style="width: 260px"
          />
          <span>&nbsp;&nbsp;&nbsp;&nbsp;秒</span>
          <!-- <el-text type="danger" size="small">限制手环升级时长，当到达指定时长则停止升级任务。</el-text> -->
        </el-form-item>
        <el-form-item v-if="form.radio == 1&&form.updateLimit==2" label="升级数量" prop="wb_count">
          <el-input-number
            v-model="form.wb_count"
            placeholder="请输入手环升级数量"
            class="mx-4"
            :min="0"
            :max="10000"
            :step="1"
            step-strictly
            controls-position="right"
            style="width: 260px"
          />
          <el-text type="danger" size="small">限制手环升级数量，当指定数量升完则停止升级任务。</el-text>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 记录 -->
    <el-dialog :title="titleRecord" v-model="openRecord" width="90%" append-to-body>
      <el-row :gutter="20">
        <el-col :span="5" :xs="24">
          <el-card class="box-card">
            <template v-slot:header>
              <div class="clearfix">
                <span>任务信息</span>
              </div>
            </template>
            <div class="list-group-top-none">
              <ul class="list-group list-group-striped">
                <li class="list-group-item">
                  <el-icon class="cpu"><plus /></el-icon>固件类型
                  <div class="pull-right">
                    <dict-tag v-if="recordData.firmware&&recordData.firmware1" :options="firmware_type" :value="[recordData.firmware.firmwareType, recordData.firmware1?.firmwareType]" />
                    <dict-tag v-else :options="firmware_type" :value="recordData[recordData.firmware?'firmware':'firmware1']['firmwareType']" />
                  </div>
                </li>
                <li class="list-group-item">
                  <el-icon class="cpu"><plus /></el-icon>下载目录
                  <div class="pull-right">
                    {{ recordData.path || "--" }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />版本号
                  <div class="pull-right">
                    {{recordData.firmware? `BIN( ${recordData.firmware?.version} )`:''}}
                    <span v-if="recordData.firmware&&recordData.firmware1">/</span>
                    {{recordData.firmware1? `FS( ${recordData.firmware1?.version} )`:'' }}
                    <!-- {{ recordData.firmware.version || "--" }} -->
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />强制更新
                  <div class="pull-right">
                    <dict-tag :options="ota_update_mode" :value="recordData?.updateMode" />
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />网关全部
                  <div class="pull-right">
                    <el-tag v-if="recordData.gw_full">是</el-tag>
                    <el-tag v-else type="danger"> 否</el-tag>
                    <span v-if="recordData?.gw_mac">({{ recordData.gw_mac.split(',').length }})</span>
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />手环全部
                  <div class="pull-right">
                    <el-tag v-if="recordData.wb_full">是</el-tag>
                    <el-tag v-else type="danger">否</el-tag>
                    <span v-if="recordData?.wb_mac">({{ recordData.wb_mac.split(',').length }})</span>
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />已完成数量
                  <div class="pull-right">
                    <span v-if="successCount>0" style="color: #67c23a;">{{ successCount || 0 }}</span>
                    <span v-else>--</span>
                    <span > (共：{{ totalDevices || 0 }})</span>
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />创建时间
                  <div class="pull-right">
                    {{ recordData.time }}
                  </div>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
        <el-col :span="19" :xs="24">
          <el-card class="detail-box">
            <template v-slot:header>
              <div class="clearfix">
                <span>最近数据</span>
                共查找到<b style="color:#F56C6C">{{ totalRecord || 0 }}</b>条
              </div>
            </template>
            <!-- <el-form
                  :model="queryParamsDetail"
                  ref="queryDetailRef"
                  :inline="true"
                >
                  <el-form-item label="网MAC地址" prop="gw_mac">
                    <el-input
                      v-model="queryParamsDetail.gw_mac"
                      placeholder="请输入网关MAC地址"
                      clearable
                      style="width: 200px"
                      @keyup.enter="handleQueryDetail"
                    />
                  </el-form-item>
                  <el-form-item label="创建时间">
                    <el-date-picker
                      v-model="queryParamsDetail.date"
                      type="datetimerange"
                      range-separator="至"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQueryDetail">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQueryDetail">重置</el-button>
                  </el-form-item>
                </el-form> -->
            <el-table
              v-loading="loadingRecord"
              :data="recordList"
              size="small"
              max-height="800px"
            >
            <el-table-column
              label="序号"
              width="60"
              align="center"
              fixed="left"
              prop="index"
            >
              <template #default="scope">
                {{ (queryParamsRecoed.pageNum - 1) * queryParamsRecoed.pageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              label="任务编号"
              align="center"
              fixed="left"
              prop="taskid"
            />
            <el-table-column
              label="网关MAC"
              min-width="150"
              fixed="left"
              align="center"
              prop="gw_mac"
            >
              <template #default="scope">
                <!-- 根据网关MAC生成不同的颜色 -->
                <el-tag :style="{ backgroundColor: getGatewayTagColor(scope.row.gw_mac) }">
                  {{ scope.row.gw_mac }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="手环MAC"
              min-width="150"
              align="center"
              prop="wb_mac"
            />
            <el-table-column label="状态" align="center" prop="action">
              <template #default="scope">
                <dict-tag :options="action_ota" :value="scope.row.action" />
              </template>
            </el-table-column>
            <el-table-column label="进度" align="center" prop="value" width="180">
              <template #default="scope">
                <el-progress
                  :text-inside="true"
                  :stroke-width="15"
                  :percentage="scope.row.value == null ? 0 : Number(scope.row.value)"
                  :status="
                    scope.row.action == 'error'
                      ? 'exception'
                      : scope.row.action == 'success'
                      ? 'success'
                      : ''
                  "
                ></el-progress>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              align="center"
              prop="time"
              width="180"
            />
              <el-table-column
                label="操作"
                fixed="right"
                width="150"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="ChromeFilled"
                    @click="() => handleOperate(scope.row, 'telnet')"
                    >终端</el-button>
                  <el-dropdown style="--el-dropdown-menu-item-hover-bg-color: var(--el-color-primary-light-9);vertical-align: middle;">
                    <el-button link type="primary">
                      <el-icon><DArrowRight /></el-icon> 更多
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'red')" style="color: #f56c6c;">红灯</el-dropdown-item>
                        <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'green')" style="color: #67c23a;">绿灯</el-dropdown-item>
                        <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'blue')" style="color: #409EFF;">蓝灯</el-dropdown-item>
                        <el-dropdown-item icon="Bell" @click="() => handleOperate(scope.row, 'buzzer')" style="color: #e6a23c;">蜂鸣</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
            <!-- <pagination
              v-show="totalRecord > 0"
              :layout="'total, sizes, prev, pager, next'"
              :total="totalRecord"
              :small="true"
              v-model:page="queryParamsRecoed.pageNum"
              v-model:limit="queryParamsRecoed.pageSize"
              @pagination="getRecords"
              style="max-width: 100%; margin: 0 auto"
            /> -->
          </el-card>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ota">
import { updateFirmwaresById } from "@/api/system/user";
import { getType } from "@/api/system/dict/type";
import {
  createOTA,
  getOtaTaskList,
  getOtaTaskById,
  deleteOtaTaskById,
  mqttOtaUpgrade,
  getFirmwaresListByType,
  getTaskById
} from "@/api/system/firmware/ota";
import { getClassGwControlLed } from "@/api/system/school/class";
import { getGatewayList } from "@/api/system/firmware/gateway";
import { getWristbandList } from "@/api/system/firmware/wb";
import { reactive, ref } from "vue";
// 定义 savePath 变量
const savePath = ref(''); 
// 假设从环境变量获取路径，这里可以根据实际情况修改
savePath.value = import.meta.env.VITE_SAVE_PATH; 
const { proxy } = getCurrentInstance();
const { action_ota, firmware_type, ota_update_mode } = proxy.useDict(
  "action_ota",
  "firmware_type",
  "ota_update_mode"
);
console.log("firmware_type>>>>",firmware_type);

const otaList = ref([]);
const firmwaresLists = ref([]);
const firmwaresAllLists = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const gatewayList = ref([]);
const wristbandList = ref([]);
const ota_update_limit = ref([
  { label: "不限制", value: 0 },
  { label: "开启时间限制", value: 1 },
  { label: "开启数量限制", value: 2 },
]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
    status: undefined,
  },
  rules: {
    firmwareid: [
      { required: true, message: "固件名称不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路径不能为空", trigger: "blur" }],
    duration: [{ required: true, message: "升级时限不能为空", trigger: "blur" }],
    wb_count: [{ required: true, message: "手环数量不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

const record =reactive({
  recordData: null,
  recordList: [],
  recordDetail: [],
  loadingRecord: false,
  openRecord: false,
  titleRecord: "",
  totalRecord: 0,
  totalDevices: 0,
  successCount: 0,
  queryParamsRecoed: {
    pageNum: 1,
    pageSize: 10
  },
})
const { recordData, recordList, loadingRecord, openRecord, titleRecord, totalRecord, totalDevices, successCount, queryParamsRecoed, recordDetail } = toRefs(record);

function rawChange(val) {
  if (!val) {
  }
}
// 定义 getGatewayTagColor 函数，根据网关MAC生成不同的颜色
const getGatewayTagColor = (gwMac) => {
  // 简单示例：根据MAC地址的哈希值生成颜色
  let hash = 0;
  for (let i = 0; i < gwMac.length; i++) {
    hash = gwMac.charCodeAt(i) + ((hash << 5) - hash);
  }
  const hue = hash % 360; // 色相值范围 0 - 359
  return `hsl(${hue}, 70%, 80%)`;
};
/** 查询OTA任务列表 */
function getList() {
  loading.value = true;
  getOtaTaskList(queryParams.value).then((response) => {
    console.log("OTA任务列表", response);
    otaList.value = response.data.data;
     total.value = response.data.total;
    loading.value = false;
  }).catch((err)=>{
    console.log('err', err)
  })
}

// 固件列表
function getFirmwaresLists(){
  getFirmwaresListByType().then((response) => {
    // console.log("固件列表",response);
    const { data, msg, code } = response;
    if (code === 200) {
      console.log('firmwaresLists', data)
      firmwaresLists.value = data;
      firmwaresAllLists.value = [...data.wb,...data.bin,...data.fs]
    } else {
      firmwaresLists.value = [];
      firmwaresAllLists.value = [];
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    title: null,
    full: 0,
    path: "/store/firmware/last.bin",
    radio: 1,
    firmwareid: "",// 固件id
    firmwareid_1: "", // 固件fs id
    gw_mac: [], // 网关
    wb_mac: [], // 手环网关
    gw_full: 0,
    wb_full: 0,
    duration: undefined,
    wb_count: undefined,
    updateMode: 'updown',
    updateLimit: 0,
    isprod: null
  };
  proxy.resetForm("OTARef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 获取网关和手环数据
  initGatewayWristbandData();
  open.value = true;
  title.value = "添加OTA任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getOtaTaskById(id).then((response) => {
    // console.log(response);
    form.value = response.data;
    open.value = true;
    title.value = "修改OTA任务";
  });
}

/** OTA任务选择固件 带出固件类型 */
function firmwareChange(el,value) {
  const selectedFirmware = firmwaresLists.value[el].find((dict) => dict.id === value);
  console.log('OTA任务选择固件: ', selectedFirmware)
  form.value.isprod = selectedFirmware?.isprod || null;
  // form.value.firmwareType = selectedFirmware.firmwareType; //value.firmwareType
  // form.value.version = selectedFirmware.version;
  form.value.full = 0;
  form.value.gw_mac = [];
  form.value.gw_full = 0;
  form.value.wb_mac = [];
  form.value.wb_full = 0;
  // form.value.force = true;
  // form.value.remain = true;
  form.value.duration = undefined;
  form.value.wb_count = undefined;
  // console.log('OTA任务选择固件', form.value)
}

/** 网关勾选全部 */
function gwFullChange (event, label) {
  // 清空网关
  form.value.gw_mac = []
  // 取消勾选全部时，初始长期更新设置 并disabled
  if(event === '0') form.value.remain = true
}

/** 手环网关勾选全部 */
function wbMacChange(event, label) {
  // 清空手环网关
  form.value.wb_mac = []
  // 取消勾选全部时，初始长期更新设置 并disabled
  if(event === '0') form.value.remain = true
}

/** 初始化网关和手环的mac数据 */
function initGatewayWristbandData() {
  // 网关列表
  getGatewayList().then((response) => {
    console.log('gateway_list', response.data);
    const { data, msg, code } = response;
    gatewayList.value = code === 200 ? data?.data : [];
  });
  // 手环列表
  getWristbandList().then((response) => {
    console.log('wristband_list', response.data);
    const { data, msg, code } = response;
    wristbandList.value = code === 200 ? data?.data : [];
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["OTARef"].validate((valid) => {
    if (valid) {
      if(form.value.radio == 2 && (!form.value.firmwareid && !form.value.firmwareid_1)){
        proxy.$modal.msgError("必须选择一个网关固件");
        return
      }
      if(form.value.gw_full != 1&&form.value.gw_mac?.length<=0){
        proxy.$modal.msgError("请选择进行升级的网关！");
        return
      }
      if(form.value.radio == 1 && form.value.wb_full != 1&&form.value.wb_mac?.length<=0){
        proxy.$modal.msgError("请选择要升级的手环！");
        return
      }
      const params = {
        ...form.value,
        gw_mac: form.value.gw_full != 1 && form.value.gw_mac.length >0 ? form.value.gw_mac.join(','):'',
        wb_mac: form.value.wb_full != 1 && form.value.wb_mac.length >0 ? form.value.wb_mac.join(','):'',
      };
      if (form.value.id != undefined) {
        // console.log(form.value);
        updateFirmwaresById(params).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("OTA任务修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("OTA任务修改失败");
          }
        });
      } else {
        // console.log(form.value);
        form.value.dictType = 'firmware_type';
        createOTA({
          ...params,
          dictType: form.value.dictType
        }).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("OTA任务创建成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("OTA任务创建失败");
          }
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id
  proxy.$modal
    .confirm('是否确认删除编号为"' + ids + '"的数据项？')
    .then(function () {
      return deleteOtaTaskById(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 升级操作 */
function handleUpgrade(row) {
  console.log('升级参数', row)
  // const params = {
  //   gw_mac: row.gw_mac,
  //   taskId: row.id,
  //   firmwareid: row.firmwareid,
  //   localPath: row.path,
  //   force: row.force||false,
  // }
  proxy.$modal.confirm(`是否现在升级任务编号为 ${row.id} 的任务？`).then(function () {
    return mqttOtaUpgrade(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("开始升级");
  }).catch(() => {});
};

function handleRecord(row) {
  console.log('记录参数', row)
  recordData.value = row
  loadingRecord.value = true;
  openRecord.value = true;
  titleRecord.value = `任务记录（${row.id})`;
  console.log("获取任务记录数据入参: ", recordData.value,row.id);
  getTaskById(row.id).then((response) => {
    console.log("获取任务记录数据", response);
    if (response.code === 200) {
      recordList.value = response.data?.result?.data || [];
      totalRecord.value = response.data?.result?.total || 0;
      totalDevices.value = response.data?.totalDevices || 0;
      successCount.value = response.data?.successCount || 0;
      // recordList.value = [recordData.value = row];
      // totalRecord.value = 1;
    } else {
      recordList.value = [];
      totalRecord.value = 0;
      totalDevices.value = 0;
      successCount.value = 0;
    }
  }).finally(() => {
    loadingRecord.value = false;
  });
}

/** 详情取消按钮 */
function cancelDetail() {
  resetDetail();
}

/** 详情表单重置 */
function resetDetail() {
  recordData.value = null
  loadingRecord.value = false;
  openRecord.value = false;
  titleRecord.value = "";
  recordList.value = [];
  totalRecord.value = 0;
  totalDevices.value = 0;
  successCount.value = 0;
}

function getRecords () {
  loadingRecord.value = true;
  // proxy.get("system/post/list", {
  //   ...queryParams.value
  // }).then((response) => {
  //   if (response.data.code === 200) {
  //     recordList.value = response.data.data;
  //     totalRecord.value = response.data.total;
  //   } else {
  //     recordList.value = [];
  //     totalRecord.value = 0;
  //   }
  //   loadingRecord.value = false;
  // });
};

/** 导出按钮操作 */
function handleExport() {
  /*proxy.download("system/post/export", {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`);*/
}
/** 重置固件ID选择 */
function resetFirmwareIds() {
  form.value.firmwareid = undefined
  form.value.firmwareid_1 = undefined
  form.value.updateLimit = 0
  form.value.duration = undefined
  form.value.wb_count = undefined
  form.value.wb_mac = []
  form.value.wb_full = 0
  form.value.gw_mac = []
  form.value.gw_full = 0
  form.value.path = '/store/firmware/last.bin'
  form.value.updateMode = 'updown'
  form.value.remain = false
  form.value.isprod = null
}
function handleOperate(row, type) {
  if(type == 'buzzer'){
    // 蜂鸣器操作
    proxy.$modal.msgError("蜂鸣器操作即将开放");
    return
  }
  if(type == 'telnet'){
    // 生成 32位长度数字+字母的token，用于连接BeConsole
    const token = Math.random().toString(36).substring(2, 34);
    getClassGwControlLed({
      action: "telnet",
      gw_mac: row.gw_mac,
      token: token,
      // url: `wss://beconsole-proxy.zhiyu.school/device?token=${token}`,
    }).then((res) => {
      console.log("等待连接BeConsole res", res);
      proxy.$modal.msgSuccess("连接BeConsole");
      // 打开BeConsole
      window.open(`https://beconsole.become.cool/?connType=ws&connUrl=wss://beconsole-proxy.zhiyu.school/terminal?token=${token}`);
    });
  }
}
function handleLight(row, color) {
  console.log("闪灯 选择", row, color);
  const colorValue = color === 'red' ? {
    red: 1,// 0-255, 0:不亮, 255需转1因为硬件暂不支持
    green: 0,
    blue: 0,
  } : color === 'green' ? {
    red: 0,
    green: 1,
    blue: 0,
  } : color === 'blue' ? {
    red: 0,
    green: 0,
    blue: 1,
  } : {
    red: 1,
    green: 1,
    blue: 1,
  };
  console.log("闪灯 入参 ", {
    action: "led",
    gw_mac: row.gw_mac,
    led1: colorValue});
  getClassGwControlLed({
    action: "led",
    gw_mac: row.gw_mac,
    led1: colorValue,
  }).then((res) => {
    console.log("闪灯 res", res);
    proxy.$modal.msgSuccess("闪灯成功");
  });
}
getFirmwaresLists();
getList();
</script>
<style lang="scss" scoped>
.list-group-top-none .list-group-striped > .list-group-item {
  border-top: none;
}
.detail-box {
  :deep(.pagination-container .el-pagination) {
    right: 20px;
  }
}
</style>